package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("login")
    @ResponseBody
    public JsonResult login(String username, String password){
        try {
           Employee employee = employeeService.login(username,password);
            //把当前登录用户存在session中
            //session.setAttribute("USER_IN_SESSION",employee);
            UserContext.setUserInSession(employee);
            //如果不是管理员就需要查询权限信息
            if (!employee.isAdmin()){
                List<String> permissions = permissionService.selectByEmpId(employee.getId());
                //session.setAttribute("EXPRESSION_IN_SESSION",permissions);
                UserContext.setExpressionInSession(permissions);
            }
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false,e.getMessage());
        }
    }

    @RequestMapping("logout")
    public String logout(HttpSession session){
        session.invalidate(); //销毁会话
        return "redirect:/login.html";
    }
}
